import {getBestNode, tokenTransfer} from "./nodes";
import Base58 from "./base58";
import AsyncStorage from "@react-native-async-storage/async-storage";
import {Alert} from "react-native";
import {addTx} from "./pendingTxs";
import {Net} from "../screens/axios";

export const NFTView_TitleSize = 14;
export const NFTView_IDSize = 11;
const baseUrl = async () => {
    const BestNodeUrl = await getBestNode();
    return BestNodeUrl;
};

const request = async (params: any) => {
    const query = [];
    for (const k in params) {
        query.push(`${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`);
    }
    let urlBase = await baseUrl();
    const url = `${urlBase}?${query.join('&')}`;
    console.log('【NFT_URL】:'+url);//TODO 2021-03-07
    const response = await fetch(url);
    return response.json();
};
//获取合约全称，包括ERC20和NFT
export const getNFTContractName = async (contract:string) => {
    const res =  await request({
        cmd: 'callFun',
        consAddress:contract,
        data:"name()",
    });
    return res;
}
//获取地址的所有NFT合约以及我的NFT数量
export const getNFTContracts = async (address:string) => {
    const res =  await request({
        cmd: 'GetNFTProperty',
        address:address,
    });
    return res;
}
//获取NFT详细数据
export const getNFTDetail = async (contract:string,id:string|number) => {
    const res =  await request({
        cmd: 'callFun',
        consAddress:contract,
        data:`tokenMetaData("${id}")`
    });
    return res;
}
//获取地址在某个合约的NFT
export const getMyNFTSByContract = async (address:string,contract:string) => {
    let res =  await request({
        cmd: 'callFun',
        consAddress:contract,
        data:`tokenOwnersAll("${address}")`
    });
    // console.log(`getMyNFTSByContract`)
    res = JSON.parse(res);
    let resList = [];
    for(let key in res)
    {
        resList.push(res[key]);
    }
    return resList;
}
//获取我所有的NFT合约和NFT
export const getNFTContractsList = async (address:string) => {
    console.log(`开始获取NFT合约列表`)
    let contractRes = await getNFTContracts(address);
    let keys = Object.keys(contractRes);
    if(keys.length==0)
    {
        return [];
    }
    // console.log(`NFT的合约:`+keys);
    // console.log(keys);
    // console.log(contractRes)
    // console.log(contractRes[keys[0]])
    let NFTContractsTemp = [];
    for(let i = 0 ; i < keys.length ; i++)
    {
        let dataStr = contractRes[keys[i]];
        let dataList = dataStr.split(":");
        let name = dataList[0];
        let myNFTS = JSON.parse(dataList[1]);
        let contract = dataList[2];
        let NFTContract = {name,myNFTS,contract}
        // console.log(NFTContract)
        NFTContractsTemp.push(NFTContract);
    }
    return NFTContractsTemp;
}
//根据id和合约获取NFT详情
export const getNFTDetailList = async (contract:string,idList: string[]) => {
    let resList = [];
    for(let i = 0 ; i < idList.length; i++ )
    {
        try {
            let id = idList[i];
            let detailTemp = await getNFTDetail(contract, id);
            let detailRes = Base58.decode(detailTemp);
            let detail:any = "";
            if (detailRes.toLowerCase().indexOf("http") === 0 || detailRes.toLowerCase().indexOf("http") === 1) {
                const url = detailRes
                let response = await Net(url,"");
                detail = response;
            } else {
                detail = JSON.parse(detailRes);
            }

            let resTemp = {id, detail}
            resList.push(resTemp)
        }catch (e) {

        }
        console.log(`getNFTDetailList------》End`)
    }
    return resList;
}
//发送NFT
export const sendNFT = async (seed:any,sender:string,contract:string,to:string,id:string|number) => {
    const lang = await AsyncStorage.getItem('@lang');
    let Tip = "";
    if(lang=="zh")
        Tip = "交易发送失败，请稍后重试";
    else
        Tip = "Fails to send transaction, retry again";
    let data = "transfer(\"" + to + "\"," + "\"" + id + "\")";
    let tx = await tokenTransfer(seed, sender, contract, data,  `SendNFT from ${sender} to ${to}`, to);
    if (tx.reason!=1)
    {
        Alert.alert(tx.reason.toString(), Tip);
        return false;
    }
    else
    {
        await addTx(tx);
        return true;
    }
}



//根据我添加的合约获取数据（用于主页）
export const getMyAddNFTContractsDetail = async (address:string) => {
    let myAddNFTContracts = await getMyAddNFTs(address);
    let res = []
    for(let i = 0 ; i < myAddNFTContracts.length ; i++)
    {
        res[i] = myAddNFTContracts[i];
        let contract = myAddNFTContracts[i].contract;
        let myNFTS = await getMyNFTSByContract(address,contract);
        res[i].myNFTS = myNFTS;
    }
    return res;
}
//获取我所添加的NFT的地址信息
export const getMyAddNFTs = async (address:string) => {
    let addNFTSStr = await AsyncStorage.getItem("myAddNFTList") ;
    if(!addNFTSStr)
    {
        return [];
    }
    let addNFTS = JSON.parse(addNFTSStr);
    return addNFTS;

}
export const removeMyAddNTF = async (address:string,contract:string) => {
    let myAddNFTList = await getMyAddNFTs(address);
    let index = myAddNFTList.findIndex((item:any) =>item.contract===contract);
    if(index>=0)
    {
        myAddNFTList.splice(index,1);
    }
    await AsyncStorage.setItem("myAddNFTList",JSON.stringify(myAddNFTList));
}
export const addMyAddNTF = async (address:string,contract:string,name:string) => {
    let myAddNFTList = await getMyAddNFTs(address);
    let index = myAddNFTList.findIndex((item:any) =>item.contract===contract);
    if(index >= 0)
    {
        return ;
    }
    myAddNFTList.push({contract,name});
    await AsyncStorage.setItem("myAddNFTList",JSON.stringify(myAddNFTList));
}
//操作我添加的NFT合约 增删查
export const modifyMyAddNFTS = async (address:string,contract:string,model:string,name:string) => {
    console.log(model+"myAddNFTS")
    switch (model) {
        case "get":
            return await getMyAddNFTs(address);
        case "remove":
            return await removeMyAddNTF(address,contract);
        case "add":
            return await addMyAddNTF(address,contract,name)
    }
}

